package com.wisdom.system.service.impl.sys;

import com.github.pagehelper.Page;
import com.wisdom.system.dao.sys.SysParamMapper;
import com.wisdom.system.dao.sys.SysUserMapper;
import com.wisdom.system.entity.base.PageRequest;
import com.wisdom.system.entity.base.PageResult;
import com.wisdom.system.entity.pojo.SysUserInfo;
import com.wisdom.system.entity.sys.SysParam;
import com.wisdom.system.entity.sys.SysUser;
import com.wisdom.system.common.annotation.ValidationUnique;
import com.wisdom.system.common.exception.LogicException;
import com.wisdom.system.common.mybatis.PageUtil;
import com.wisdom.system.common.mybatis.SqlUtil;
import com.wisdom.system.common.util.StringUtil;
import com.wisdom.system.service.job.JobLogService;
import com.wisdom.system.service.sys.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * 用户 服务实现类
 *
 * @Date 2019/3/7 10:53
 * @author: GuoHonghui
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysParamMapper sysParamMapper;

    @Autowired
    private JobLogService jobLogService;

    /**
     * 新增用户
     *
     * @param sysUser
     * @return
     */
    @Override
    @ValidationUnique(key = {"loginCode"}, msg = {"登录账号已存在！"})
    public int addSysUserInfo(SysUser sysUser) {
        //通过读取参数配置的默认密码
        Example example = new Example(SysParam.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("paramKey","USER_DEFAULT_INIT_PASSWORD");
        SysParam sysParam = sysParamMapper.selectOneByExample(example);
        //判断系统参数是否有配置
        if (sysParam == null){
            throw LogicException.of("系统参数未配置用户初始化默认密码！");
        }
        //判断读取的密码是否为空
        if (StringUtil.isEmpty(sysParam.getParamValue())){
            throw LogicException.of("默认密码为空，请先在系统参数中配置默认初始密码！");
        }
        //设置用户默认密码123456
        String password = new BCryptPasswordEncoder().encode(sysParam.getParamValue());
        sysUser.setPassword(password);
        sysUser.setAddTime(new Date());
        return sysUserMapper.insert(sysUser);
    }

    /**
     * 修改用户
     *
     * @param sysUser
     * @return
     */
    @Override
    @ValidationUnique(key = {"loginCode"}, msg = {"用户账号已存在！"},excludeSelf = true)
    public int updateSysUserInfo(SysUser sysUser) {
        return sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }


    /**
     * 删除用户（单个）
     *
     * @param id
     * @return
     */
    @Override
    public int delSysUserInfo(String id) {
        return sysUserMapper.deleteByPrimaryKey(id);
    }

    /**
     * 删除用户（批量删除）
     *
     * @param ids
     * @return
     */
    @Override
    public int delSysUserList(String ids) {
        String[] idArray = ids.split(",");
        Example example = new Example(SysUser.class);
        example.createCriteria().andIn("id", Arrays.asList(idArray));
        return sysUserMapper.deleteByExample(example);
    }

    /**
     * 根据主键id获取用户详情
     *
     * @param id
     * @return
     */
    @Override
    public SysUser getSysUserInfo(String id) {
        return sysUserMapper.getSysUserInfo(id);
    }

    @Override
    public List<SysUser> getSysUserList(String keyword) {
        Example example = new Example(SysUser.class);
        Example.Criteria criteria1 = example.createCriteria();
        criteria1.andLike("name", SqlUtil.likeEscapeH(keyword))
                .orLike("loginCode", SqlUtil.likeEscapeH(keyword))
                .orLike("email", SqlUtil.likeEscapeH(keyword))
                .orLike("phone", SqlUtil.likeEscapeH(keyword))
                .orLike("pyCode",SqlUtil.likeEscapeH(keyword))
                .orLike("wbCode",SqlUtil.likeEscapeH(keyword));
        example.and(criteria1);
        example.orderBy("addTime").desc();
        return sysUserMapper.selectByExample(example);
    }

    /**
     * 获取用户列表
     *
     * @param fkDepartmentCode
     * @param keyword
     * @return
     */
    @Override
    public List<SysUser> getSysUserListByDepartmentCode(String fkDepartmentCode, String keyword) {
        if (!StringUtil.isEmpty(fkDepartmentCode)) {
            return sysUserMapper.getSysUserList(fkDepartmentCode, SqlUtil.likeEscapeH(keyword));
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 获取分页用户列表
     *
     * @param keyword
     * @param pageRequest
     * @return
     * @Param fkDepartmentCode
     */
    @Override
    public PageResult<SysUser> getSysUserPageListByDepartmentCode(String fkDepartmentCode, String keyword, PageRequest pageRequest) {
        Page<?> page = PageUtil.startPageAllowNull(pageRequest.getPageNum(), pageRequest.getPageSize());
        return new PageResult<>(getSysUserListByDepartmentCode(fkDepartmentCode, keyword), page.getTotal());
    }

    @Override
    public PageResult<SysUser> getSysUserPageList(String keyword, PageRequest pageRequest) {
        Page<?> page = PageUtil.startPageAllowNull(pageRequest.getPageNum(), pageRequest.getPageSize());
        return new PageResult<>(getSysUserList(keyword), page.getTotal());
    }


    /**
     * 更新用户状态
     *
     * @param id
     * @param state
     * @return
     */
    @Override
    public int updateSysUserState(String id, int state) {
        HashMap<String, Object> hashMap = new HashMap<>(2);
        hashMap.put("id", id);
        hashMap.put("state", state);
        return sysUserMapper.updateSysUserState(hashMap);
    }

    /**
     * 修改用户密码
     *
     * @return
     */
    @Override
    public int updateSysUserPassword(SysUserInfo sysUserInfo) {
        Example example = new Example(SysUser.class);
        example.createCriteria().andEqualTo("id", sysUserInfo.getId());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        SysUser sysUser = sysUserMapper.selectOneByExample(example);
        //判断输入的旧密码是否正确
        boolean matches = encoder.matches(sysUserInfo.getOldPwd(), sysUser.getPassword());
        if (!matches) {
            throw LogicException.of("输入的旧密码不正确！");
        }
        //判断新密码和确认密码是否一致
        if (!sysUserInfo.getNewPwd().equals(sysUserInfo.getConfirmPwd())) {
            throw LogicException.of("两次输入的密码不一致！");
        }
        //加密新密码
        String password = new BCryptPasswordEncoder().encode(sysUserInfo.getNewPwd());
        Map<String, Object> map = new HashMap<>();
        map.put("id", sysUserInfo.getId());
        map.put("password", password);
        return sysUserMapper.updatePassword(map);
    }

    /**
     * 修改用户信息
     *
     * @param sysUserInfo   用户id
     * @return map
     */
    @Override
    public int updateSysUserInfo(SysUserInfo sysUserInfo) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("id", sysUserInfo.getId());
        map.put("name", sysUserInfo.getName());
        map.put("email", sysUserInfo.getEmail());
        map.put("mobilePhone", sysUserInfo.getPhone());
        return sysUserMapper.updateUserinfo(map);
    }

}
